const Path = require("path");
const File = require("fs/promises");
const md5 = require("md5");
const uuid = require("uuid");
const xlsx = require("xlsx");

module.exports = {
  /**
   * 读取文件夹下所有模块 https://www.jianshu.com/p/abb844bacc51
   * @param path 路径
   * @param rule 读取规则
   */
  async get_modules_of_dir(path, rule = "") {
    //若不是绝对路径 转为绝对路径
    if (!Path.isAbsolute(path)) {
      path = Path.resolve(path);
    }
    const files = await File.readdir(path);
    const reg = new RegExp(rule);
    return files.reduce((res, cur) => {
      if (reg.test(cur)) {
        res.push(require(`${path}/${cur}`));
      }
      return res;
    }, []);
  },

  /**
   * @param {number} nums 获取指定位的排列组合 例：nums=3 => ['100', '110', '111', '101', ...]
   */
  get_permutation_combinations(nums) {
    const res = [];
    for (let i = 0; i <= nums; i++) {
      let str = "1".repeat(i) + "0".repeat(nums - i),
        j = 0,
        arr = [],
        set_time = 0,
        reset = () => (j = arr.length = set_time = 0);
      while (true) {
        arr[(j + 1) % nums] = str[j];
        set_time++;
        if (set_time === nums) {
          let _str = arr.join("");
          if (res.includes(_str)) {
            break;
          } else {
            res.push(_str);
            str = _str;
          }
          reset();
        } else {
          j = (j + 1) % nums;
        }
      }
    }
    return res;
  },

  uuid() {
    return uuid.v4();
  },

  cryto(val, salt) {
    return md5(md5(val) + salt);
  },

  read_excel(path) {
    const wb = xlsx.readFile(path);
    const result = [];
    for (const sheet of wb.SheetNames) {
      result.push({
        sheet_name: sheet,
        raws: xlsx.utils.sheet_to_json(wb.Sheets[sheet]),
      });
    }
    return result;
  },
};
